import axios, { AxiosRequestConfig, Canceler } from 'axios'
import { message } from 'antd'
import { getCookie } from '@fallen_leaves/fe-utils'
import { MessageBox } from '../components/MessageBox'

const xhr = axios.create({
  timeout: 30000,
  headers: {},
  responseType: 'json'
})

interface CustomRequestConfig extends AxiosRequestConfig {
  isFree?: boolean
}

// 请求拦截器
xhr.interceptors.request.use(
  async (config: CustomRequestConfig) => {
    if (!config.isFree) { // 非免登录接口
      let cancel: Canceler = () => false
      const token =  getCookie('ADMIN_AUTN_TOKEN') as string
      config.cancelToken = new axios.CancelToken(c => cancel = c)
      if (!token) {
        await MessageBox.warning({
          content: '登录信息已过期，请重新登录！',
          okText: '重新登录',
          maskClosable: false,
          closable: false
        })
        window.location.replace('/admin/login')
        cancel()
      }
      config.headers = {
        ...config.headers,
        token
      }
    }
    return config
  },
  error => Promise.reject(error)
)
// 响应拦截器
xhr.interceptors.response.use(
  async response => {
    const { data, config: { responseType = 'json' } } = response
    if (responseType !== 'json') {
      return data
    }
    if (+data.code === 200) {
      return data.data || data.body
    } else if ([3001, 3002].includes(+data.code)) {
      await MessageBox.warning({
        content: '登录信息已过期，请重新登录！',
        okText: '重新登录',
        maskClosable: false,
        closable: false
      })
      window.location.replace('/admin/login')
      return
    } else {
      message.warning(data.message)
    }
    return Promise.reject(data.message)
  },
  error => {
    if (error.response) {
      let errorMsg = ''
      switch (error.response.status) {
      case 403:
        errorMsg = '无访问权限'
        break
      case 404:
        errorMsg = `请求地址出错: ${error.response?.config?.url}`
      case 500:
      case 501:
      case 502:
      case 503:
      case 504:
        errorMsg = '服务器开个小差，请稍后访问'
        break
      case 505:
        errorMsg = 'service版本不支持'
        break
      default:
        errorMsg = error.response?.data?.message || '网络请求异常'
      }
      message.warning(errorMsg)
      return Promise.reject(errorMsg)
    } else {
      message.warning('网络请求异常')
      return Promise.reject(new Error(error))
    }
  }
)

export default xhr
